<ModalDialog
  {id}
  {label}
  {title}
  shrinkWidthToFit={true}
  background="var(--main-bg)"
  on:show="onShow()"
>
  <form class="copy-dialog-form">
    <input value={text}
           ref:input
    >
    <button type="button" on:click="onClick()">
      Copy
    </button>
  </form>
</ModalDialog>
<style>
  .copy-dialog-form {
    display: grid;
    grid-template-rows: min-content min-content;
    grid-template-columns: 1fr;
    grid-gap: 10px;
    padding: 10px 20px;
    width: 400px;
    max-width: calc(100% - 40px);
  }
</style>
<script>
  import ModalDialog from './ModalDialog.html'
  import { show } from '../helpers/showDialog.js'
  import { close } from '../helpers/closeDialog.js'
  import { oncreate as onCreateDialog } from '../helpers/onCreateDialog.js'
  import { toast } from '../../toast/toast.js'
  import { doubleRAF } from '../../../_utils/doubleRAF.js'

  function copyFromInput (input) {
    // workarounds for iOS, via https://stackoverflow.com/a/34046084
    const range = document.createRange()
    range.selectNodeContents(input)
    const selection = window.getSelection()
    selection.removeAllRanges()
    selection.addRange(range)
    input.setSelectionRange(0, 9999999)
    document.execCommand('copy')
  }

  export default {
    oncreate () {
      onCreateDialog.call(this)
    },
    methods: {
      show,
      close,
      onClick () {
        const { input } = this.refs
        copyFromInput(input)
        toast.say('intl.copiedToClipboard')
        this.close()
      },
      onShow () {
        const { text } = this.get()
        const { input } = this.refs
        // double raf is to work around a11y-dialog trying to set the input
        doubleRAF(() => {
          input.focus()
          input.setSelectionRange(0, text.length)
        })
      }
    },
    data: () => ({
      text: ''
    }),
    components: {
      ModalDialog
    }
  }
</script>
